//
//  BannerView.swift
//  ZhiQianJia
//
//  Created by  Apple on 2017/8/3.
//  Copyright © 2017年 LiFu. All rights reserved.
//用于图片轮播的自定义控件
//可兼容作为引导图
//TOYO:增加点击处理（可以实现UICollectionview的代理方法）
//问题：全局变量控制有些没有时效性。

import UIKit

//点击banner 回调
typealias clickedClosure = (_ selectedIndex:Int) -> Void

class LFBannerCell: UICollectionViewCell {
    var imageView:UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        imageView = UIImageView(frame: self.bounds)
        self.addSubview(imageView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        imageView = UIImageView(frame: self.bounds)
        self.addSubview(imageView)
    }
}

enum BannerPagePosition{
    case left
    case middle
    case right
   
}

class LFBannerView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {

     //轮播图片数组
    var images:[UIImage] = [UIImage()]{
        willSet{
            if newValue.count == 0 {
                print("______bannerView:警告！传入图片不能为0")
                self.images = [UIImage()]
            }
            if newValue.count == 1 {
                self.isAutoScroll = false
                self.collectionView.isScrollEnabled = false
            }else {
                self.isAutoScroll = true
                self.collectionView.isScrollEnabled = true
            }
        }
        didSet{
            self.updatePageView()
            self.collectionView.reloadData()
        }
    }
    
    var timer:DispatchSource!   //使用GCD定时器
    var imageView:UIImageView!
    var pageIndex:Int = 0
    var contentSize:CGSize!
    var collectionView:UICollectionView!
    var flowLayout:UICollectionViewFlowLayout!
    var pageView:UIPageControl!
    
    var clickedClosure : clickedClosure?
    var interval:Int = 3{       //时间间隔,默认三秒轮播一次
        willSet{
            self.timer.scheduleRepeating(deadline: .now(), interval: .seconds(newValue))
        }
    }
    var isHiddenPageGroup:Bool = false{  //是否隐藏小圆点组
        willSet{
            if newValue {
                 pageView.alpha = 0.0
            }else {
                pageView.alpha = 1.0
            }
           
        }
    }
    var isAutoScroll:Bool = true{//是否自动滚动
        willSet{
            if !newValue {
                self.timer.cancel()
                timer.suspend()
            }else {
                self.prepareTimer()
            }
        }
    }
    
    
    var position = BannerPagePosition.middle
    var pageTintColor = UIColor.gray     //未选中点颜色
    var currentPageColor = UIColor.white //指示点的颜色（白色）
    
    //MARK:-init method
    
    init(frame:CGRect,images:[UIImage]) {
        super.init(frame: frame)
        self.images = images
        self.prepareCollectionView()
        self.preparePageView()
        self.prepareTimer()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.prepareCollectionView()
        self.prepareTimer()
        self.preparePageView()
    }

    
    
     //MARK:-view setup
    
    func prepareCollectionView() -> Void {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0 //注意，当为水平滑动时，这个就是行间距。
        layout.scrollDirection = .horizontal
        self.flowLayout = layout
        
        let collection = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        collection.isScrollEnabled = true
        collection.isPagingEnabled = true
        collection.showsHorizontalScrollIndicator = false
        collection.showsVerticalScrollIndicator = false
        collection.backgroundColor = .clear
        collection.bounces = false
        self.collectionView = collection
        self.addSubview(collection)
        collection.register(LFBannerCell.self, forCellWithReuseIdentifier: "BannerCell")
        
        
    }
    //可以在这里自定义page控制器
    fileprivate func preparePageView() -> Void {
        let pageFrame=CGRect()//(x: 0, y: 0, width: , height:48)
        let page = UIPageControl(frame: pageFrame)
        
        self.addSubview(page)
        self.pageView = page
        updatePageView()
    }
    
    fileprivate func updatePageView() -> Void {
        let page = self.pageView!
        page.numberOfPages = images.count
        page.currentPage = pageIndex
        page.updateCurrentPageDisplay()
        page.currentPage = 0
        page.alpha = 0.7
        page.pageIndicatorTintColor = pageTintColor
        page.currentPageIndicatorTintColor = currentPageColor
        if isHiddenPageGroup {
            page.alpha = 0
        }
    }
    
    //GCD设置定时器
    func prepareTimer() -> Void {
       
        if self.timer != nil {
            self.timer = nil
        }
       
        self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) as! DispatchSource
        self.timer.scheduleRepeating(deadline:  .now() + DispatchTimeInterval.seconds(interval), interval: .seconds(interval))
        self.timer.setEventHandler {
            UIView.animate(withDuration: 0.25, animations: {  //【learn】添加切换动画
                self.collectionView.setContentOffset(CGPoint(x: self.bounds.width*2, y:0 ), animated: true)
            }, completion:nil)
        }
        //启动定时器
        self.timer.resume()
        
    }
    
    
    //MARK: - layouSubviews
    //父视图frame改变的时候自动调用。必须实现，否则会出现适配的问题
    override func layoutSubviews() {
        super.layoutSubviews()
        if self.flowLayout != nil {
           self.flowLayout.itemSize = self.bounds.size
        }
        if self.collectionView != nil{
            self.collectionView.frame = self.bounds
            print(3*self.bounds.width)
            self.collectionView.contentSize = CGSize(width: 3*self.bounds.width, height: self.bounds.height)
            self.collectionView.contentOffset = CGPoint(x: self.bounds.width, y: 0)
            
            let pageY = self.collectionView.bounds.height-CGFloat(10)
            var pageX = CGFloat(0)
            
            if position == .middle {
                pageX = (self.collectionView.bounds.width)/2
            }else if position == .left{
                pageX = CGFloat(10*self.images.count)
            }else if position == .right{
                pageX = self.collectionView.bounds.width - CGFloat(10*self.images.count)
            }
            pageView.center = CGPoint(x: pageX, y: pageY)
        }
        
    }
    
    //MARK: - UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerCell", for: indexPath) as! LFBannerCell
        var i:Int
        if indexPath.row == 0 {
            i = (images.count+pageIndex-1)%(images.count)
        }else if indexPath.row == 1 {
            i = pageIndex
        }else{
            i = (pageIndex+1)%(images.count)
        }
       
        let bannerImage = images[i]
        cell.imageView.image = bannerImage
        return cell
    }
    //点击cell设置回调 【注意：indexPath永远是中间的那个 1 】
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if clickedClosure != nil {
            clickedClosure!(pageIndex)
        }
        
    }
    
    
    //MARK: - UIScrollViewDelegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if (scrollView.contentOffset.x == scrollView.bounds.width*2) //左滑和自动滑动
        {
            pageIndex = (pageIndex+1)%(images.count)
            self.collectionView.reloadData()
            scrollView.contentOffset = CGPoint(x: scrollView.bounds.width, y: 0)
            self.pageView.currentPage = pageIndex
        }else if scrollView.contentOffset.x == 0{//右滑
            pageIndex = (pageIndex-1+images.count)%(images.count)
            self.collectionView.reloadData()
            scrollView.contentOffset = CGPoint(x: scrollView.bounds.width, y: 0)
            self.pageView.currentPage = pageIndex
        }
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.timer.suspend() //暂停定时器
        
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.timer.resume()
    }
    
    //MARK: - 点击回调
    ///点击回调
    
    func bannerClicked(closure: @escaping clickedClosure) -> Void {
        clickedClosure = closure
    }
    
   

}
